package cn.liuweiwei.util;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtils {

	// 发送方邮箱地址
	private static final String senderEmailAddress = "vivi.love.java@qq.com";
	// 发送邮件的标题
	private static String senderEmailHeader = "验证码";
	// 开启服务的授权码
	private static final String authecticationPassword = "wctivgppyxaidiei";

	/**
	 * 设置邮件的标题、默认为验证码
	 * 
	 * @param header
	 */
	public static void setEmailHeader(String header) {
		senderEmailHeader = header;
	}

	/**
	 * 发送邮件的方法
	 * 
	 * @param receiverEmailAdderss 接收方的邮箱地址
	 * @param emailMessage         要发送的邮件信息
	 * @throws Exception
	 */
	public static void sendMail(String receiverEmailAdderss, Object emailMessage) throws Exception {
		Properties properties = new Properties();
		properties.setProperty("mail.transport.protocol", "SMTP");
		properties.setProperty("mail.host", "smtp.qq.com");
		properties.setProperty("mail.smtp.auth", "true");
		properties.setProperty("mail.smtp.port", "587"); //qq

		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(senderEmailAddress, authecticationPassword);
			}
		};
		Session session = Session.getInstance(properties, authenticator);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(senderEmailAddress));
		message.setRecipient(RecipientType.TO, new InternetAddress(receiverEmailAdderss));
		message.setSubject(senderEmailHeader);

		message.setContent(emailMessage, "text/html;charset=utf-8");
		Transport.send(message);
	}

	// 测试
	public static void main(String[] args) throws Exception {
			sendMail("2500247684@qq.com", "哈哈哈");
	}

}
